//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;

using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

using Mindscape.BackgroundMotion.Core.Properties;

namespace Mindscape.BackgroundMotion.Core.Validators
{
  /// <summary>
  /// A validator that checks that a field contains some data
  /// </summary>
  public class RequireValidatorAttribute : CustomValidatorAttribute
  {
    private readonly int _maxLength;

    public RequireValidatorAttribute(string fieldName, int maxLength)
      : base(fieldName)
    {
      _maxLength = maxLength;
    }

    /// <summary>
    /// Does the create validator.
    /// </summary>
    /// <param name="targetType">Type of the target.</param>
    /// <returns></returns>
    protected override Validator DoCreateValidator(Type targetType)
    {
      return new RequireValidator(FieldName, _maxLength);
    }
  }

  /// <summary>
  /// A validator that checks that a field contains some data
  /// </summary>
  public class RequireValidator : CustomValidator<string>
  {
    private readonly int _maxLength;

    public RequireValidator(string fieldName, int maxLength)
      : base(fieldName)
    {
      _maxLength = maxLength;
    }

    /// <summary>
    /// Performs the validation
    /// </summary>
    /// <param name="objectToValidate">The object to validate.</param>
    /// <param name="currentTarget">The current target.</param>
    /// <param name="key">The key.</param>
    /// <param name="validationResults">The validation results.</param>
    protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
    {
      new StringLengthValidator(1, RangeBoundaryType.Inclusive, _maxLength, RangeBoundaryType.Inclusive, MessageTemplate)
        .Validate(objectToValidate, validationResults);
    }

    /// <summary>
    /// Gets the message resource.
    /// </summary>
    /// <value>The message resource.</value>
    protected override string MessageResource
    {
      get { return Resources.ValueIsRequired; }
    }
  }
}